<template>
  <div>
    <a-transfer class="tree-transfer"
                :list-style="listStyle"
                :data-source="transferDataSource"
                :target-keys="targetKeys"
                :render="(item) => item.name"
                :show-select-all="false"
                :titles="titles"
                :locale="locale"
                show-search
                @change="onChange"
                @search="onSearch">
      <template slot="children"
                slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }">
        <a-tree v-if="direction === 'left' && calTreeData.length"
                blockNode
                show-icon
                defaultExpandAll
                :selectedKeys="[...selectedKeys, ...targetKeys]"
                :treeData="calTreeData"
                @select="
            (_, props) => {
              onChecked(props, selectedKeys, targetKeys, itemSelect);
            }
          ">
          <i slot="folder"
             class="xicon-folder"
             style="color: #FFD524;" />
          <i slot="doc"
             class="xicon-form-text"
             style="color: #0077FF" />
        </a-tree>
      </template>
    </a-transfer>
  </div>
</template>
<script>
  let INIT_DATA = [];
  const SELECT_TEMPLATE = 'template';

  export default {
    props: {
      value: {
        type: Object,
        default: () => {}
      },
      type: {
        type: String
      },
      allCount: {
        type: Number
      }
    },
    data() {
      return {
        listStyle: {
          width: '356px',
          height: '464px'
        },
        treeData: [],
        targetKeys: [],
        transferDataSource: [],
        titles: [$.i18n('cap.template.data.check.allData'), $.i18n('ctp.dr.selected.data.title.js')],
        locale: {
          itemUnit: $.i18n('common.item.label'),
          itemsUnit: $.i18n('common.item.label'),
          notFoundContent: $.i18n('serial.list.empty.msg'),
          searchPlaceholder: $.i18n('serial.search.key.placeholder')
        },
        // 确认时，通过targetKeys获取对象数据
        mapData: {}
      };
    },
    async created() {
      if (this.type === SELECT_TEMPLATE) {
        let templatePanel = this.value?.templatePanel;
        if (templatePanel) {
          let value = templatePanel;
          if (templatePanel.startsWith('C_')) {
            value = templatePanel.split('_')[1];
          }
          this.targetKeys.push(value);
        }
      } else {
        let value = this.value?.realSenderPanel?.split('|')[1];
        if (value) {
          this.targetKeys.push(value);
        }
      }
      this.treeData = await this.getTreeData();
      INIT_DATA = this.jsonCopy(this.treeData);
      this.flatten(this.jsonCopy(this.treeData));
    },
    computed: {
      calTreeData() {
        return this.handleTreeData(this.treeData, this.targetKeys);
      },
      /**
       * 父组件调用获取结果值
       * @returns {{value: {}, key: string}}
       */
      valueChange() {
        const targetKeys = this.targetKeys;
        let targetObj = this.mapData[targetKeys[0]];
        let retValue = {};
        if (this.type === SELECT_TEMPLATE) {
          if (!targetObj) {
            return retValue;
          }
          retValue.text = targetObj.name;
          if (targetObj.type === 'template') {
            retValue.templatePanel = targetObj.id;
            return retValue;
          }
          if (targetObj.unionIds && targetObj.unionIds.indexOf(',') > -1) {
            retValue.templatePanel = targetObj.unionIds
              .split(',')
              .map((id) => 'C_' + id)
              .join(',');
            return retValue;
          }
          retValue.templatePanel = 'C_' + targetObj.id;
          return retValue;
        }
        if (!targetObj) {
          return retValue;
        }
        retValue.text = targetObj.name;
        retValue.realSenderPanel = targetObj.type + '|' + targetObj.id;
        if (!(targetObj.type === 'Account' || targetObj.type === 'Department')) {
          retValue.senderPanel = targetObj.type + '|' + targetObj.id;
          return retValue;
        }
        let memberDetail = this.findAllMember4ChildrenTree(targetObj);
        if (memberDetail.count > 50) {
          //大于规定值则不考虑兼职/副岗
          retValue.senderPanel = targetObj.type + '|' + targetObj.id;
          return retValue;
        }
        retValue.senderPanel = memberDetail.detail;
        return retValue;
      }
    },
    methods: {
      findAllMember4ChildrenTree(node) {
        //设置默认值
        let memberDetail = {};
        let detailArr = [];

        let allChildrenNodes = [];
        this.getAllChildrenNodes(node, allChildrenNodes);

        for (let i = 0; i < allChildrenNodes.length; i++) {
          if ('Member' == allChildrenNodes[i].type) {
            detailArr.push(allChildrenNodes[i].type + '|' + allChildrenNodes[i].id);
          }
        }
        memberDetail.detail = detailArr.join(',');
        memberDetail.count = detailArr.length;

        return memberDetail;
      },
      getAllChildrenNodes(treeNode, result) {
        if (treeNode.children.length) {
          let childrenNodes = treeNode.children;
          if (childrenNodes) {
            for (let i = 0; i < childrenNodes.length; i++) {
              result.push(childrenNodes[i]);
              result = this.getAllChildrenNodes(childrenNodes[i], result);
            }
          }
        }
        return result;
      },
      flatten(list = []) {
        list.forEach((item) => {
          this.transferDataSource.push(item);
          this.flatten(item.children);
        });
      },
      handleTreeData(data, targetKeys = []) {
        data.forEach((item) => {
          item['disabled'] = targetKeys.includes(item.key);
          if (item.children) {
            this.handleTreeData(item.children, targetKeys);
          }
        });
        return data;
      },
      isChecked(selectedKeys, eventKey) {
        return selectedKeys.indexOf(eventKey) !== -1;
      },
      async getTreeData() {
        let _this = this;
        const memberId = window._currentUser.id;
        const method =
          this.type === SELECT_TEMPLATE ? 'getTreeData4PendingTemplate' : 'getTreeData4PendingStaff';
        const params = { memberId };
        console.log('this.allCount', this.allCount);
        if (this.allCount != undefined) {
          params.allCount = parseInt(this.allCount, 10);
        }
        console.log('params', params);
        const args = `managerMethod=${method}&arguments=${JSON.stringify(params)}`;
        const url = `${
          window._ctxPath
        }/ajax.do?method=ajaxAction&managerName=pendingManager&rnd=${Math.random()}`;
        const data = await window.axios.post(url, args).then((ret) => ret?.data);
        return this.arrayToTree(data);
      },
      arrayToTree(items = []) {
        // 存放结果集
        let res = [];
        // 判断对象是否有某个属性
        let map = {};

        // 边做map存储，边找对应关系
        for (const i of items) {
          map[i.id] = {
            ...i,
            title: i.name,
            key: i.id,
            children: map[i.id] ? map[i.id].children : []
          };
          let newItem = map[i.id];
          newItem.slots = { title: 'customTitle' };
          this.mapData[i.id] = newItem;
          if (i.pId === null || i.id === i.pId) {
            res.push(newItem);
          } else {
            if (!map[i.pId]) {
              map[i.pId] = {
                children: []
              };
            }
            map[i.pId].children.push(newItem);
            map[i.pId].slots = { icon: 'folder' };
            newItem.slots = { icon: 'doc' };
          }
        }
        return res;
      },
      onChange(targetKeys, direction, moveKeys) {
        if (direction === 'right') {
          this.targetKeys = [moveKeys[moveKeys.length - 1]];
        } else if (direction === 'left') {
          this.targetKeys = [];
        }
      },
      onChecked(e, checkedKeys, targetKeys, itemSelect) {
        const { eventKey } = e.node;
        let newCheckedKeys = [...targetKeys];
        newCheckedKeys.push(checkedKeys[checkedKeys.length - 1]);
        let checked = !this.isChecked(newCheckedKeys, eventKey);
        itemSelect(eventKey, checked);
        if (checkedKeys.length) {
          checkedKeys.forEach((key) => itemSelect(key, false));
        }
      },
      onSearch(direction, value) {
        if (direction === 'left') {
          if (value) {
            this.treeData = this.handleData(this.jsonCopy(INIT_DATA), value);
            return;
          }
          this.treeData = this.jsonCopy(INIT_DATA);
        }
      },
      handleData(data = [], value) {
        let result = [];
        for (let i = 0; i < data.length; i++) {
          let item = data[i];
          if (item.children) {
            let children = this.handleData(item.children, value);
            if (children.length) {
              item.children = children;
              result.push(item);
            } else if (item.title.indexOf(value) > -1) {
              delete item.children;
              result.push(item);
            }
          } else if (item.title.indexOf(value) > -1) {
            result.push(item);
          }
        }
        return result;
      },
      jsonCopy(data) {
        return JSON.parse(JSON.stringify(data));
      }
    }
  };
</script>
<style lang="scss" inline>
  .tree-transfer {
    .ant-transfer-list:first-child {
      width: 50%;
      flex: none;
    }

    .ant-transfer-list-body-with-search {
      display: flex;
      flex-direction: column;
    }

    .ant-transfer-list-body-customize-wrapper {
      overflow-y: auto;
      flex: 1 1 auto;
    }

    .ant-tree-node-content-wrapper {
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
      white-space: nowrap;
    }
  }
</style>
